import Vue from 'vue'
import VueRouter from 'vue-router'
import {
  getToken
} from '@/utils/token.js'

Vue.use(VueRouter)

const routes = [{
    path: '/',
    redirect: '/layout'
  },
  {
    path: '/login',
    component: () => import( /* webpackChunkName: "Login" */ '@/views/Login'),
    beforeEnter(to, from, next) {
      // 当已经是登录状态的时候，不允许切换到登录页面
      if (getToken() && getToken().length > 0 && to.path === '/login') {
        next('layout/home') // 不跳转
      } else {
        next() // 其他情况放行
      }
    }
  },
  {
    path: '/layout',
    component: () => import( /* webpackChunkName: "Layout" */ '@/views/Layout'),
    redirect: '/layout/home',
    children: [{
        path: 'home',
        component: () => import( /* webpackChunkName: "Home" */ '@/views/Home'),
        meta: {
          scrollT: 0 // 保存首页离开时，滚动条的位置
        }
      },
      {
        path: 'user',
        component: () => import( /* webpackChunkName: "User" */ '@/views/User')
      }
    ]
  },
  {
    path: '/search',
    component: () => import( /* webpackChunkName: "Search" */ '@/views/Search')
  },
  {
    path: '/search_result/:kw',
    component: () => import( /* webpackChunkName: "SearchResult" */ '@/views/Search/SearchResult.vue')
  },
  {
    path: '/articleDetail',
    component: () => import( /* webpackChunkName: "ArticleDetail" */ '@/views/ArticleDetail')
  },
  {
    path: '/user_editor',
    component: () => import( /* webpackChunkName: "UserEdit" */ '@/views/User/UserEdit')
  },
  {
    path: '/chart',
    component: () => import( /* webpackChunkName: "Chart" */ '@/views/Chart')
  }
]

const router = new VueRouter({
  routes
})

// 路由的全局前置守卫，在路由每次发生跳转之前，会执行此函数
// 此函数可以决定是否跳转/取消/强制中断切换到别的路由
// router.beforeEach((to, from, next) => {
//   // 当已经是登录状态的时候，不允许切换到登录页面
//   if (getToken() && getToken().length > 0 && to.path === '/login') {
//     next(false) // 不跳转
//   } else {
//     next() // 其他情况放行
//   }
// })

export default router
